package com.lovo.test.service.impl;

import com.lovo.test.dao.UserDAO;
import com.lovo.test.dao.impl.UserDAOImpl;
import com.lovo.test.pojo.UserDO;
import com.lovo.test.service.UserService;
import jdk.jshell.EvalException;

import java.io.EOFException;
import java.util.concurrent.ExecutionException;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UserDO getByUserNameAndPwd(String userName, String pwd) {
        return userDAO.getByUserNameAndPwd(userName, pwd);
    }


    @Override
    public void saveMoney(int id, int money) {
        UserDO userDO = userDAO.getById(id);
        userDO.setMoney(userDO.getMoney() + money);
        userDAO.update(userDO);
    }

    @Override
    public void getMoney(int id, int money) throws Exception {
        UserDO userDO = userDAO.getById(id);
        if (money>userDO.getMoney()){
            throw new Exception("余额不足");
        }
        userDO.setMoney(userDO.getMoney()-money);
        userDAO.update(userDO);
    }

    @Override
    public void setPwd(int id,String oldPwd, String newPwd) throws Exception {
        UserDO userDO = userDAO.getById(id);
        if (!oldPwd.equals(userDO.getPassWord())){
            throw new Exception("旧密码不匹配");
        }
        userDO.setPassWord(newPwd);
        userDAO.update(userDO);

    }

    @Override
    public void turnMoney(UserDO userDO,String name, int money) throws NullPointerException,EOFException {
        UserDO objUserDO = userDAO.getByName(name);
        if (objUserDO==null||objUserDO.getUserName().equals(userDO.getUserName())){
            throw new NullPointerException("不能给自己转账或查无此人");
        }
        if (money > userDO.getMoney()){
            throw new EOFException("账户余额不足");
        }

        userDO.setMoney(userDO.getMoney()-money);
        objUserDO.setMoney(objUserDO.getMoney()+money);
        userDAO.turnUpdate(userDO,objUserDO);
    }
}
